<template>
  <div class="authority">
    <div class="gva-table-box unit">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addArea">新增组织</el-button>
      </div>
      <el-table :data="tableData" row-key="id">
        <el-table-column align="left" label="组织名称" prop="name"></el-table-column>
        <el-table-column align="left" label="级别">
          <template #default="scope">
             <span v-if="scope.row.type==1">省</span>
             <span v-if="scope.row.type==2">市</span>
             <span v-if="scope.row.type==3">县</span>
             <span v-if="scope.row.type==4">乡</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="排序" prop="sort" />
        <el-table-column align="left" fixed="right" label="操作" min-width="160">
          <template #default="scope">
            <el-button type="primary" link icon="edit" @click="editArea(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link icon="delete" @click="delArea(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-drawer v-model="dialogFormVisible" :size="appStore.drawerSize" :before-close="handleClose" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ dialogTitle }}</span>
          <div>
            <el-button @click="closeDialog"> 取 消 </el-button>
            <el-button type="primary" @click="enterDialog"> 确 定 </el-button>
          </div>
        </div>
      </template>
      <el-form v-if="dialogFormVisible" ref="areaForm" label-width="110" :model="form" :rules="rules">
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="行政区划代码">
          <el-input v-model="form.code" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :value="1" size="large">省</el-radio>
            <el-radio :value="2" size="large">市</el-radio>
            <el-radio :value="3" size="large">县</el-radio>
            <el-radio :value="4" size="large">乡</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级区域">
          <el-cascader :disabled="form.type == 1" :options="tableData" :props="props1" clearable v-model="pids" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model.number="form.sort" placeholder="请输入"/>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import {
  getUnitList,
  deleteUnit,
  createUnit,
  updateUnit,
  createRegion,
  getRegionList,
  deleteRegion,
  updateRegion
} from '@/api/unit'
import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { ElMessage, ElMessageBox } from 'element-plus'
import { sortBySort } from '@/utils/format'
defineOptions({
  name: 'Area'
})
const appStore = useAppStore()

const form = ref({
  name: '',
  type: 1,
  parentId: 0,
  sort: null,
  code: ''
})
const dialogFormVisible = ref(false)
const rules = reactive({
  name: [{ required: true, message: '请输入组织名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
})
const areaForm = ref(null)
const pids = ref([])
const props1 = {
  checkStrictly: true,
  label: 'name',
  value: 'id'
}
const initForm = () => {
  areaForm.value.resetFields()
  form.value = {
    name: '',
    type: 1,
    parentId: 0,
    sort: null,
    code: ''
  }
  pids.value = []
}
const isEdit = ref(false)
const dialogTitle = ref('新增组织')
const addArea = () => {
  dialogTitle.value = '新增组织'
  isEdit.value = false
  dialogFormVisible.value = true
}
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}
const tableData = ref([])
// 查询
const getTableData = async () => {
  const res = await getRegionList()
  if (res.code == 200) {
    tableData.value = sortBySort(res.result)
  }
}
getTableData()

onMounted(() => {

})
const enterDialog = async () => {
  areaForm.value.validate(async (valid) => {
    if (valid) {
      form.value.parentId = form.value.type == 1 ? 0 : pids.value[pids.value.length - 1]
      let res
      if (isEdit.value) {
        res = await updateRegion(form.value)
      } else {
        res = await createRegion(form.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}
const delArea = (row) => {
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await deleteRegion(row.id)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}
const handleClose = (done) => {
  initForm()
  done()
}
const editArea = async (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑组织'
  form.value = JSON.parse(JSON.stringify(row))
  form.value.regionId = form.value.id
  pids.value = getPids(row)
  dialogFormVisible.value = true
}

const getPids = (row) => {
  let res = []
  if (row.type == 1) {
    return []
  } else if (row.type == 2) {
    tableData.value.forEach(item => {
      if (item.children.length > 0) {
        item.children.forEach(m => {
          if (m.id == row.id) {
            res.push(item.id)
          }
        })
      }
    })
  } else if (row.type == 3) {
    tableData.value.forEach(item => {
      if (item.children.length > 0) {
        item.children.forEach(m => {
          if (m.children.length > 0) {
            m.children.forEach(n => {
              if (n.id == row.id) {
                res.push(item.id)
                res.push(m.id)
              }
            })
          }
        })
      }
    })
  }else{
    tableData.value.forEach(item => {
      if (item.children.length > 0) {
        item.children.forEach(m => {
          if (m.children.length > 0) {
            m.children.forEach(n => {
              if (n.children.length > 0){
                n.children.forEach(k=>{
                  if (k.id == row.id){
                    res.push(item.id)
                    res.push(m.id)
                    res.push(n.id)
                  }
                })
              }
            })
          }
        })
      }
    })
  }
  return res
}
</script>

<style lang="scss">
.flex {
  .area {
    flex: 2;
    background-color: #fff;
    margin: 0.5rem 20px 0.5rem 0;
  }

  .unit {
    flex: 4;
  }
}
</style>
